<?php
namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RolePermission extends BaseModel
{
    use HasFactory;

    const CREATED_AT='create_time';
    const UPDATED_AT= null;

    protected $table = 'role_permission';


    /**
     * 获取角色对应的所有的权限列表
     * @param $role_ids 角色id  数组  
     */
    public function getRolePermission($role_ids){
        if(!is_array($role_ids)) $role_ids = explode(',' , $role_ids);
        $permission_id_arr = $this->whereIn('role_id' , $role_ids)->groupBy('permission_id')->pluck('permission_id')->toArray();
        $permissions = Permission::select('id','permission_name','api_path')->whereIn('id' , $permission_id_arr)->where('is_del' , 1)->where('is_admin' , 2)->get()->toArray();

        return $permissions; 
    }

    /**
     * 添加(修改)角色权限 ，删除多余的，增加新增的
     * @param role_id 角色id
     * @param permission_ids 权限id  多个 逗号 拼接
     * @param $type 类型  add 新增，直接增加   change 需要查询
     */
    public function rolePermissionChange($role_id , $permission_ids , $type = 'change'){
        $permission_ids = empty($permission_ids) ? [] : explode(',' , $permission_ids);
        $permission_ids = array_filter(array_unique($permission_ids));
        if($type == 'add'){
            $permission_ids_ed = [];
        }else{
            $permission_ids_ed = $this->where('role_id' , $role_id)->groupBy('permission_id')->pluck('permission_id')->toArray();
        }
        $permission_ids_del = array_diff($permission_ids_ed,$permission_ids); //对比返回在 $permission_ids_ed 中但是不在 $permission_ids 的数据删除
        $permission_ids_add = array_diff($permission_ids,$permission_ids_ed); //对比返回在 $permission_ids 中但是不在 $permission_ids_ed 的数据添加
        if(!empty($permission_ids_del)) $this->whereIn('permission_id' , $permission_ids_del)->where('role_id' , $role_id)->delete();
        $data = [];
        foreach($permission_ids_add as $key=>$val){
            $data[$key]['role_id'] = $role_id; 
            $data[$key]['permission_id'] = $val; 
            $data[$key]['create_time'] = date('Y-m-d H:i:s'); 
        }
        if(!empty($data)) $this->insert($data);
    }



}
